package dao;

import entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import tool.MyBatisUtil;

import java.io.Reader;

public class UserDaoImpl implements UserDao{
    //mybatis 操作数据库步骤3个核心类
    SqlSessionFactoryBuilder builder = null;
    SqlSessionFactory factory = null;//SqlSessionFactory由SqlSessionFactoryBuilder构建
    SqlSession sqlSession = null;//真正操作数据库的核心对象 执行增删改 SqlSession由SqlSessionFactory构建

    //输入流读取配置文件
    Reader reader = null;


    @Override
    public int getcount() {
        int result =-1;

        try{
            //读取配置文件
            reader = Resources.getResourceAsReader("mybatis-config.xml");
           // 构建SqlSessionFactoryBuilder
            builder = new SqlSessionFactoryBuilder();
           // 构建SqlSessionFactory
            factory = builder.build(reader);
           // 构建SqlSession
            sqlSession = factory.openSession();
            //执行数据库的操作dao接口的全限定名称+id名
            //result = sqlSession.selectOne("dao.UserDao.findall");//需要解析dao接口的配置文件
            result = sqlSession.getMapper(UserDao.class).getcount();//mapper接口方式
            return result;

        }catch (Exception e){
            e.printStackTrace();
            return -1;

        }finally {
            //释放资源
            MyBatisUtil.closeSession();
        }

    }

    @Override
    public User getUser(Integer userid) {
        User user = null;

        try{

            // 构建SqlSession
            sqlSession = MyBatisUtil.getSession();
            //执行数据库的操作dao接口的全限定名称+id名
            //result = sqlSession.selectOne("dao.UserDao.findall");//需要解析dao接口的配置文件
            user = sqlSession.getMapper(UserDao.class).getUser(userid);//mapper接口方式
            return user;

        }catch (Exception e){
            e.printStackTrace();
            return null;

        }finally {
            //释放资源
            MyBatisUtil.closeSession();
        }

    }
}
